package com.wutongyu.mannyburger;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class ProductAdapter extends BaseAdapter {

    private final Context context;
    private final List<Product> productList;
    private final List<Product> selectedProducts;
    private final TextView bottomCartTextView;
    private double totalPrice;
    private OnTotalPriceChangedListener totalPriceChangedListener;

    public ProductAdapter(Context context, List<Product> productList, List<Product> selectedProducts, TextView bottomCartTextView) {
        this.context = context;
        this.productList = productList;
        this.selectedProducts = selectedProducts;
        this.bottomCartTextView = bottomCartTextView;
    }

    @Override
    public int getCount() {
        return productList.size();
    }

    @Override
    public Object getItem(int position) {
        return productList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return productList.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.product_list_item, parent, false);
            holder = new ViewHolder();
            holder.productImageView = convertView.findViewById(R.id.product_image);
            holder.productNameTextView = convertView.findViewById(R.id.product_name);
            holder.productDescriptionTextView = convertView.findViewById(R.id.product_description);
            holder.productPriceTextView = convertView.findViewById(R.id.product_price);
            holder.productQuantityTextView = convertView.findViewById(R.id.product_quantity);
            holder.btnDecrease = convertView.findViewById(R.id.btn_decrease);
            holder.btnIncrease = convertView.findViewById(R.id.btn_increase);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Product product = productList.get(position);
        
        // 设置商品信息
        holder.productNameTextView.setText(product.getName());
        holder.productPriceTextView.setText("¥" + product.getPrice());
        
        // 设置商品描述（如果有）
        if (product.getDescription() != null && !product.getDescription().isEmpty()) {
            holder.productDescriptionTextView.setText(product.getDescription());
            holder.productDescriptionTextView.setVisibility(View.VISIBLE);
        } else {
            holder.productDescriptionTextView.setVisibility(View.GONE);
        }
        
        // 设置商品图片（如果有）
        if (product.getImageResId() != 0) {
            holder.productImageView.setImageResource(product.getImageResId());
        } else {
            holder.productImageView.setImageResource(R.drawable.bg); // 默认图片
        }
        
        // 更新商品数量
        updateQuantityDisplay(holder, product);
        
        // 设置增加按钮点击事件
        holder.btnIncrease.setOnClickListener(v -> {
            int quantity = product.getQuantity();
            product.setQuantity(quantity + 1);
            
            if (quantity == 0) {
                // 第一次添加到选中列表
                selectedProducts.add(product);
                // 显示减号按钮
                holder.btnDecrease.setVisibility(View.VISIBLE);
            }
            
            updateQuantityDisplay(holder, product);
            updateTotalPrice();
        });
        
        // 设置减少按钮点击事件
        holder.btnDecrease.setOnClickListener(v -> {
            int quantity = product.getQuantity();
            if (quantity > 0) {
                product.setQuantity(quantity - 1);
                
                if (product.getQuantity() == 0) {
                    // 从选中列表中移除
                    selectedProducts.remove(product);
                    // 隐藏减号按钮
                    holder.btnDecrease.setVisibility(View.GONE);
                }
                
                updateQuantityDisplay(holder, product);
                updateTotalPrice();
            }
        });
        
        // 设置商品项点击跳转到详情页
        convertView.setOnClickListener(v -> {
            Intent intent = new Intent(context, ProductDetailActivity.class);
            intent.putExtra("product_id", product.getId());
            context.startActivity(intent);
        });

        return convertView;
    }
    
    // 更新商品数量显示
    private void updateQuantityDisplay(ViewHolder holder, Product product) {
        int quantity = product.getQuantity();
        holder.productQuantityTextView.setText(String.valueOf(quantity));
        
        if (quantity > 0) {
            holder.btnDecrease.setVisibility(View.VISIBLE);
        } else {
            holder.btnDecrease.setVisibility(View.GONE);
        }
    }

    // 设置监听器setOnTotalPriceChangedListener，用于更新MainActivity购物车总金额
    public void setOnTotalPriceChangedListener(OnTotalPriceChangedListener listener) {
        this.totalPriceChangedListener = listener;
    }

    // 用于更新MainActivity购物车总金额
    private void updateTotalPrice() {
        totalPrice = 0.0;
        for (Product product : selectedProducts) {
            totalPrice += product.getPrice() * product.getQuantity();
        }
        
        // 更新购物车显示
        int totalItems = 0;
        for (Product product : selectedProducts) {
            totalItems += product.getQuantity();
        }
        
        bottomCartTextView.setText("购物车：" + totalItems + "件, 共 ¥" + String.format("%.2f", totalPrice));
        
        if (totalPriceChangedListener != null) {
            totalPriceChangedListener.onTotalPriceChanged(totalPrice);
        }
    }

    // 回调接口，用于更新OrderActivity用户订单总金额
    public interface OnTotalPriceChangedListener {
        void onTotalPriceChanged(double totalPrice);
    }

    static class ViewHolder {
        ImageView productImageView;
        TextView productNameTextView;
        TextView productDescriptionTextView;
        TextView productPriceTextView;
        TextView productQuantityTextView;
        ImageButton btnDecrease;
        ImageButton btnIncrease;
    }
}
